import Vue from 'vue'
import config from '../api/config.js'
// const graceRichText = require('@/common/richText.js');
import graceRichText from "@/common/richText.js";
// import API from '../api/apiUrl.js'
// 引入路由
import router from '../router'
import {
		Message,
} from "element-ui";

// vue在单独引入js文件中使用ElementUI的弹框,调用的时候报错了'$alert' of undefined
let vThis = new Vue();

// 引进加载
import {Loading} from 'element-ui'
import store from '../vuex/store.js'
export default {
  data() {
    return {
      hasUnReadMessage: false,
      imagePrefix: config.imagePrefix,
    }
  },
  filters: {
    // 时间格式化
    dateFormat(timestamp, fmt) {
      this.dateFormatFun(timestamp, fmt)
    },
  },
  methods: {
    // 防抖函数
    debounceNew(fn, delay) {
      var timer;
      return function () {
        var context = this;
        var args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay);
      };
    },
    // 节流
    throttleNew(fn, delay) {
      var ctx;
      var args;
      // 记录上次触发事件
      var previous = Date.now();

      var later = function () {
        fn.apply(ctx, args);
      };

      return function () {
        ctx = this;
        args = arguments;
        var now = Date.now();
        // 本次事件触发与上一次的时间比较
        var diff = now - previous - delay;

        // 如果隔间时间超过设定时间，即再次设置事件触发的定时器
        if (diff >= 0) {
          // 更新最近事件触发的时间
          previous = now;
          setTimeout(later, delay);
        }
      };
    },
    // 最长六位小数
    toFixed6(num, digit=6){
      if (typeof num == 'string'){
        num = parseFloat(num);
      }
      if(!num) return;
      num = num.toFixed(digit).replace(/[.]?0+$/g,"");
      return num
    },
    //Loading加载
    openFullScreen(e) {
      // const loading = this.$loading({
      const loading = Loading.service({
        lock: true,
        text: e || 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      return loading;
    },
    //关闭Loading加载
    closeFullScreen(loading){
      loading.close();
    },
    // 获取url参数
    GetQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      // var r = '?redEnvelopeCode=123'
      r = r.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    // 富文本插件
    // 过滤复文本特殊符号
    filterSpecialSymbol(str) {
    	// str = str.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');
    	str = graceRichText.format(str);
    	// rich-text处理换行符
    	if(str.trim() != ''){
    		return str.split('\n').reduce((total, cur) => total += `<p>${cur}</p>`)
    	}else{
    		return str;
    	}
    	// return str;
    },
    // 对象转数组
    objTrantsArr(obj) {
      let settingObj = obj;
      let settingArr = Object.keys(settingObj).map(key => {
        //console.log(key); //为每个键名
        // console.log(settingObj);
        return settingObj[key]; //把每个对象返回出去生成一个新的数组中相当于0:{id:1}
      });
      return settingArr;
    },
    showMessageMin(options) {
      options.type = options.type || 'info';
      options.duration = options.duration || 2500;
      options.center = options.center || false;
      Message(options);
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    // 时间格式化
    dateFormatFun(timestamp, fmt) {
      if (typeof timestamp == 'string') timestamp = timestamp.replace(/-/g, '/')
      const date = new Date(timestamp)
      let monthEnglish= ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'D+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
        w: '日一二三四五六'.charAt(date.getDay()),
    	'yue': monthEnglish[new Date(new Date(timestamp)).getMonth()], // 月份
      }
      if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      // console.log('fmt',fmt)
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
    		  fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
        }
      }
      return fmt
    },
    formatDate(shijianchuo) {
    	return this.dateFormatFun(shijianchuo, 'DD-yue-YYYY hh:mm:ss')
    },
    formatNs(shijianchuo) {
    	return this.dateFormatFun(shijianchuo, 'DD-yue hh:mm')
    },
    formatY(shijianchuo) {
    	return this.dateFormatFun(shijianchuo, 'DD-yue-YYYY')
    },
    formatH(shijianchuo) {
    	return this.dateFormatFun(shijianchuo, 'hh:mm:ss')
    },
    isInteger(obj) {
      return typeof obj === 'number' && obj % 1 === 0
    },
    setImgSize(arr, size, attr) {
      if (!arr || !arr.length) return
      arr.forEach(item => {
        let str;
        if (attr) {
          str = attr;
          if (!item[str]) return
        } else {
          if (item.image) str = 'image';
          if (item.images) str = 'images';
          if (item.imageUrl) str = 'imageUrl';
          if (item.remomondImageUrl) str = 'remomondImageUrl';
          if (item.goodsImage) str = 'goodsImage';
          if (!item[str]) return
        }
        if (item[str].indexOf(size) != -1) return
        let subs = item[str].split('.');
        let len = subs.length;
        subs[len - 2] = subs[len - 2] + `_r${size}p`;
        item[str] = subs.join('.')
      })
      return arr
    },
    checkpsw(e) {
      if (!e.detail.value) return
      let val = e.detail.value;
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/g;
      if (!reg.test(val)) {
        console.log(reg.test(val));
      }
    },
    checkPswString(str) {
      // let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/g;
      let reg = /^[a-zA-Z\d]{6,16}$/g;
      if (!reg.test(str)) {
        return false
      } else {
        return true
      }
    },
    checkNameString(str) {
      // let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{3,18}$/g;
      // let reg = /^[A-Za-z0-9]{3,18}$/g;
      let reg = /^[A-Za-z0-9\u4e00-\u9fa5\-_.?@]{5,80}$/g;
      if (!reg.test(str)) {
        return false
      } else {
        return true
      }
    },
    checkPhoneString(str) {
      let reg = /^[A-Za-z0-9\u4e00-\u9fa5\-_.?@]{6,}$/g;
      if (!reg.test(str)) {
        return false
      } else {
        return true
      }
    },
    checkEmailString(str) {
      let reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!reg.test(str)) {
        return false
      } else {
        return true
      }
    },
    goProduct(product) {
      let id;
      product.goodsId ? id = product.goodsId : '';
      console.log(product);
      // uni.navigateTo({
      //   url: '/pages/product/product-detail?id=' + id
      // })
    },
    // checkNewMessage() {
    //   API.checkNewMessage().then(res => {
    //     if (res.data.status == 1 && res.data.data) {
    //       this.hasUnReadMessage = true;
    //     } else {
    //       this.hasUnReadMessage = false;
    //     }
    //   })
    // },
    multiply(n1 = 0, n2 = 0) {
      var s1 = n1.toString()
      var s2 = n2.toString()
      var l1 = (s1.split('.')[1] || '').length
      var l2 = (s2.split('.')[1] || '').length
      var r1 = Number(s1.replace('.', ''))
      var r2 = Number(s2.replace('.', ''))
      return r1 * r2 / Math.pow(10, l1 + l2)
    },
    divide(n1 = 0, n2 = 0) {
      var s1 = n1.toString()
      var s2 = n2.toString()
      var l1 = (s1.split('.')[1] || '').length
      var l2 = (s2.split('.')[1] || '').length
      var r1 = Number(s1.replace('.', ''))
      var r2 = Number(s2.replace('.', ''))
      return this.multiply((r1 / r2), Math.pow(10, l2 - l1))
    },
    add(n1 = 0, n2 = 0) {
      var s1 = n1.toString()
      var s2 = n2.toString()
      var l1 = (s1.split('.')[1] || '').length
      var l2 = (s2.split('.')[1] || '').length
      var c = Math.abs(l1 - l2)
      var m = Math.pow(10, Math.max(l1, l2))

      var r1 = 0
      var r2 = 0
      if (c > 0) {
        var cm = Math.pow(10, c)
        if (l1 > l2) {
          r1 = Number(s1.replace('.', ''))
          r2 = Number(s2.replace('.', '')) * cm
        } else {
          r1 = Number(s1.replace('.', '')) * cm
          r2 = Number(s2.replace('.', ''))
        }
      } else {
        r1 = Number(s1.replace('.', ''))
        r2 = Number(s2.replace('.', ''))
      }
      return (r1 + r2) / m
    },
    subtract(n1 = 0, n2 = 0) {
      var l1 = (n1.toString().split('.')[1] || '').length
      var l2 = (n2.toString().split('.')[1] || '').length
      var m = Math.pow(10, Math.max(l1, l2))
      var n = (l1 >= l2) ? l1 : l2
      return Number(((n1 * m - n2 * m) / m).toFixed(n))
    },
    checkLogin(myTips) {
      // console.log("myTips",myTips)
      // console.log("store",store)
      let that = this;
      const memberInfo = store.state.memberInfo || {}
      if (!memberInfo.id) {
        vThis.$alert(myTips.content, myTips.title, {
          confirmButtonText: myTips.confirm,
          callback: action => {
            if(action == 'confirm'){
              store.commit('updateIndex','#/login')
              store.commit('saveDefaultActiveIndex','')
              Vue.nextTick(function () {
                // DOM 现在更新了
                // `this` 绑定到当前实例
                router.push({path:'/login'});
              })
            }
          }
        });
        return false
      }
      return true
    },
    percent(value, fmt) {
      return `${((value ||0) *100).toFixed(fmt ||2)}%`;
    },

    percentNum(value, fmt) {
      return `${((value ||0) *100)}`;
    },
    percentT(value, fmt) {
      return `${((value ||0) *100).toFixed(fmt ||3)}`;
    },
    // 是否是手机
    isMobile(){
        let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
        // localStorage.setItem('isiphone',flag)
        localStorage.setItem('ismobile',flag?1:0);
        let goUrl = flag ? 1 : 0;
        return goUrl;
    },
    // 矿机
    sleep(time = 100) {
      return new Promise((resolve) => {
        const timer = setTimeout(() => {
          clearTimeout(timer);
          resolve();
        }, time);
      });
    },
    // 获取symbol实时行情
    realTimePrice(arr,symbol){
    	let that = this;
    	let obj = {}
    	if (arr && arr.length > 0) {
    		new Promise(resolve => {
    			obj = arr.filter(item => {
    				return item.symbol == symbol
    			})[0]
    		})
    	}
    	// console.log("obj",obj)
    	return obj
    },
    // 字面量方法设置组件多语言
    componentMultilingual(name) {
    	var names = {
    		'en-US': function() {
    			uni.setLocale('en')
    			return name;
    		},
    		'zh-CN': function() {
    			uni.setLocale('zh-Hans')
    			return name;
    		},
    		'zh-tw': function() {
    			uni.setLocale('zh-Hant')
    			return name;
    		},
    	};
    	if (typeof names[name] !== 'function') {
    		// 默认英文
    		uni.setLocale('en')
    		return false;
    	}
    	return names[name]();
    },
    // 选项卡切换选择
    listActive(arr,index){
    	let that = this;
    	let newArr = [];
    	if(arr && arr.length > 0){
    		newArr = arr.map((pItem,pIndex)=>{
          return {
            ...pItem,
            active: pIndex == index ? true : false
          }
        })
    	}
    	return newArr
    },
    routerPush(path,id,fromPage,top=true,query=false){
      if(top){
        this.scrollToTop();
      }
      if(query){
        router.push({path:path,query: query})
        return
      }
      if(id){
        if(fromPage){
          router.push({path:path,query: {[fromPage]:id}})
          return
        }
        router.push({path:path,query: {id:id}})
        return
      }
      router.push(path); //用go刷新
    },
    goBack(detal=-1){
      router.go(detal); //返回上一层
    },
    //  划过样式变化
    changeActive($event, className) {
      $event.currentTarget.className = className;
    },
    removeActive($event, className) {
      $event.currentTarget.className = className;
    },
    // 复制成功时的回调函数
    onCopyCopy(e) {
      Message.success('复制成功')
    },
    // 复制失败时的回调函数
    onErrorCopy(e) {
      Message.error('复制失败')
    },
    // 平滑的滚动页面到顶部
    scrollToTop() {
      const c = document.documentElement.scrollTop || document.body.scrollTop;
      if (c > 0) {
        window.requestAnimationFrame(this.scrollToTop);
        window.scrollTo(0, c - c / 8);
      }
    },
    // 定义一个方法来处理ref虚拟列表滚动到顶部的操作
    scrollTopRef(refName) {
      this.$nextTick(()=>{
        if(this.$refs[refName]&&this.$refs[refName].bodyWrapper){
          this.$refs[refName].bodyWrapper.scrollTop=0;
        }else {
          this.$refs[refName].scrollTop= 0;
        }
      })
    },
    //点击事件到顶部
    topScrollClick(refName) {
      this.$nextTick(() => {
        let scrollEl = this.$refs[refName];
        scrollEl.scrollTo({ top: 0, behavior: 'smooth' });
      });
    },
    //点击事件到底部
    bottomScrollClick(refName) {
      this.$nextTick(() => {
        let scrollEl = this.$refs[refName];
        scrollEl.scrollTo({ top: scrollEl.scrollHeight, behavior: 'smooth' });
      });
    },
    //尾部补零(常用13为时间戳字符串，后端返回格式不一定是13位)
    padEndFun(val,digit,num){
      if(val == '' || val == undefined || val == null){
        return ''
      }
      if(typeof val == 'number'){
        val = val.toString()
      }
      // console.log('val',val)
      let str = val.padEnd(digit, num.toString())
      return Number(str)
    },
    //头部补零
    padStartFun(val,digit,num){
      let str = val.toString().padStart(digit, num.toString())
      return Number(str)
    },
    //获取日期集合--近一个月
    get_date(num) {
      let dateArray = []
      //获取今天日期
      let myDate = new Date()
      let today = myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + "-" + myDate.getDate();
      myDate.setDate(myDate.getDate() - num)
      let dateTemp;  // 临时日期数据
      let flag = 1;
      for (let i = 0; i < num; i++) {
        dateTemp = myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + "-" + myDate.getDate()
        dateArray.push({
          date: dateTemp
        })
        myDate.setDate(myDate.getDate() + flag);
      }
      dateArray.push({
        date: today
      })
      let arr = []
      let newArr = []
      dateArray.forEach(item => {
        arr.push(item.date.split('-'))
      })
      for (let i = 0; i < arr.length; i++) {
        if (arr[i][1] < 10) {
          arr[i][1] = "0" + arr[i][1]
        }
        if (arr[i][2] < 10) {
          arr[i][2] = "0" + arr[i][2]
        }
      }
      for (let j = 0; j < arr.length; j++) {
        newArr.push(arr[j].join("-"))
      }
      // 当前日期
      let nowDate = newArr[newArr.length - 1]
      // 30天前日期
      let previousDate = newArr[0]
      // 日期区间数组
      // console.log(nowDate)
      // console.log(previousDate)
      // console.log(newArr)
      return newArr
    },
    //https://blog.csdn.net/weixin_50999303/article/details/117929221?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-117929221-blog-131976961.235%5Ev38%5Epc_relevant_default_base3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-117929221-blog-131976961.235%5Ev38%5Epc_relevant_default_base3&utm_relevant_index=14
    //获取日期集合--当月
    getMonth(timestamp) {
      const year = this.dateFormatFun(timestamp,'YYYY');
      const month = this.dateFormatFun(timestamp,'MM');
      const day = new Date(year, month, 0).getDate();
      let current_month_num = day;
      let current_month = [];
      for (let i = 1; i <= current_month_num; i++) {
        // i < 10 ? i = "0" + i : i;
        // let day = month + '月' + i + '日'
        // current_month.push(day);
        let dayNew = {
          label: month + '月' + i + '日',
          prop: i.toString(),
        }
        current_month.push(dayNew);
      }
      return current_month
    },
    // getMonth(timestamp) {
    //   const year = this.dateFormatFun(timestamp,'YYYY');
    //   const month = this.dateFormatFun(timestamp,'MM');
    //   const days = this.dateFormatFun(timestamp,'DD');
    //   const day = new Date(year, month, 0).getDate();
    //   let now = new Date(days);
    //   let current_month_num = day;
    //   let current_month = [];
    //   for (let i = 1; i <= current_month_num; i++) {
    //     let day = now.setDate(i);
    //     day = this.dateFormatFun(day,'MM-DD')
    //     current_month.push(day);
    //   }
    //   return current_month
    // },
    //获得当前月
    getNowMonth(timestamp) {
      // const date = new Date();
      // const year = date.getFullYear();
      // let month = date.getMonth() + 1;
      // month = month > 9 ? month : "0" + month;
      // const nowMonth = year + "-" + month;
      // return nowMonth;
      return this.dateFormatFun(timestamp,'YYYY-MM');
    },
    // 获取当前月的上一月
    getPreMonth(timestamp) {
      const arr = this.getNowMonth(timestamp).split("-");
      const year = arr[0]; //获取当前日期的年份
      const month = arr[1]; //获取当前日期的月份

      let year2 = year;
      let month2 = parseInt(month) - 1;
      if (month2 == 0) {
        //1月的上一月是前一年的12月
        year2 = parseInt(year2) - 1;
        month2 = 12;
      }

      // if (month2 < 10) {
      //   //10月之前都需要补0
      //   month2 = "0" + month2;
      // }
      // const preMonth = year2 + "-" + month2;
      const preMonth = month2;
      return preMonth;
    },
    // 获取当前月的下一月
    getNextMonth(timestamp) {
      const arr = this.getNowMonth(timestamp).split("-");
      const year = arr[0]; //获取当前日期的年份
      const month = arr[1]; //获取当前日期的月份

      let year2 = year;
      let month2 = parseInt(month) + 1;
      if (month2 == 13) {
        //12月的下月是下年的1月
        year2 = parseInt(year2) + 1;
        month2 = 1;
      }
      // if (month2 < 10) {
      //   //10月之前都需要补0
      //   month2 = "0" + month2;
      // }

      // const nextMonth = year2 + "-" + month2;
      const nextMonth = month2;
      return nextMonth;
    },
    // 处理选项卡返回格式
    SelectMap(obj){
      if(obj){
        let arr = obj.split(',').map((item,index)=>{
          return {
            key: index,
            value: item
          }
        })
        // arr.unshift({key:null,value:'请选择'})
        return arr
      }
      return []
    },
    // 处理功能权限显示
    // 筛选权限页面
    authListFilter(arr, name, pageName){
      if(arr&&arr.length>0){
        const obj = arr.filter(item => item.name == 'customManagement')[0]
        if(obj.children&&obj.children.length>0){
          return  obj.children.filter((item)=>{
            return  item.name == pageName
          })[0]
        }
        return {}
      }
      return {}
    },
    // 筛选权限页面按钮功能
    authFilter(obj, name){
      if(obj){
        if(obj.children&&obj.children.length>0){
          let arr = obj.children.filter((item)=>{
             return  item.name == name
          })
          if(arr&&arr.length>0){
            return arr[0].check == 1
          }
          return false
        }
        return false
      }
      return false
    },
    // 筛选权限页面按钮功能符合长度
    authFilterLen(obj, ...arr){
      if(obj){
        if(obj.children&&obj.children.length>0){
          const arrNew = obj.children.filter((item)=>{
            return  arr.includes(item.name)&&item.check
          })
          return arrNew
        }
        return []
      }
      return []
    },
    // 下载明细等url
    downUrl(href){
      window.location.href=href
    },
    // 下载zip包
    downZip(url){
      const iframe = document.createElement("iframe")
      iframe.style.display = "none" // 防止影响页面
      iframe.style.height = 0 // 防止影响页面
      iframe.src = url
      console.log('iframe.src', iframe.src)
      document.body.appendChild(iframe) // 这一行必须，iframe挂在到dom树上才会发请求
    },
    // select显示文字
    showSelect(arr, value, label = 'label') {
      let name = ''
      if(arr&&arr.length>0){
        name = arr.filter((item)=>{
          return  item.value == Number(value)
        })[0][label]
      }
      return name
    },
    showSelectTxt(arr, value, label = 'label') {
      let name = ''
      if(arr&&arr.length>0){
        name = arr.filter((item)=>{
          return  item.value == value
        })[0][label]
      }
      return name
    },
    // 是否为数字
    isNumber(val){
      if(typeof val=='number' && !isNaN(val)){
        return true
      }
      return false
    },
    // 数组扁平化、去重、排序
    newArray(arr) {
      while (arr.some(Array.isArray)) {
        arr = [].concat(...arr)
      }
      arr = [...new Set(arr)].sort((a, b) => a - b)
      return arr
    },
    // 判断数据类型
    dataType(tgt, type) {
      const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
      return type ? dataType === type : dataType;
    },
    // 是否为空数组
    isNullArray(arr) {
      return Array.isArray(arr) && !arr.length;
    },
    // 是否为空对象
    isNullObject(obj) {
      return this.dataType(obj, "object") && !Object.keys(obj).length;
    },
    // 是否为数字
    myIsNaN(val){
      return typeof val == 'number' && !isNaN(val)
    },
    // 是否为数字非时间戳
    isTimestampNumber(val){
      if(typeof val=='number' && !isNaN(val) && !this.isTimestamp(val)){
        return true
      }
      return false
    },
    // 判断是否为时间戳
    isTimestamp(timestamp) {
      const regex = /^\d{13}$/;
      if (regex.test(timestamp)) {
        const date = new Date(timestamp);
        return !isNaN(date.getTime());
      }
      return false;
    },
    toggleRowSelection(ref, row, selection) {
      const vm = this
      // umy-ui中的代码需添加“.$refs.singleTable”才能正常运行，否则会报“数据格式需要一个数组”错误
      if (vm.$refs[ref]) {
        if (vm.$refs[ref].$refs.singleTable) {
          vm.$refs[ref].$refs.singleTable.toggleRowSelection(row, selection)
        } else {
          vm.$refs[ref].toggleRowSelection(row, selection)
        }
      }
    },
    clearSelection(ref) {
      const vm = this
      if (vm.$refs[ref]) {
        vm.$refs[ref].clearSelection()
      }
    },
    // javascript中从一个对象取部分属性给另一个对象
    objfilter(obj,arr){
      return arr.reduce((iter, val) => {
        if(val in obj) {
          iter[val] = obj[val];
        }
        return iter;
      }, {});
    },
    is(val, type) {
      return toString.call(val) === `[object ${type}]`;
    },
    //判断是否为undefined或者null
    isDef(val) {
      return typeof val !== 'undefined' && typeof val !== 'null';
    },
    isUnDef(val) {
      return !this.isDef(val);
    },
    //判断是否为字符串
    isString(val) {
      return this.is(val, 'String');
    },
    //判断是否为空对象
    isEmptyNew(val) {
      if(this.isUnDef(val)){
        return true;
      }
      if (this.isArrayNew(val) || this.isString(val)) {
        return val.length === 0;
      }
      if (val instanceof Map || val instanceof Set) {
        return val.size === 0;
      }
      if (this.isObjectNew(val)) {
        return Object.keys(val).length === 0;
      }
      return false;
    },
    //判断是否为空字符串
    emptyString(val) {
      if (!this.isString(val) || this.isEmptyNew(val)) {
        return false;
      }
      let judgeFn = new RegExp(/\s+/g);
      return judgeFn.test(val);
    },
    //判断是否为对象
    isObjectNew(val) {
      return val !== null && val !== undefined && this.is(val, 'Object');
    },
    //判断是否为数组
    isArrayNew(val) {
      return val && Array.isArray(val);
    },
    //转义方法
    urlstringify(obj) {//字符串序列化
      let str = '';
      for (let key in obj) {
        if (Object.prototype.toString.call(obj[key]) === '[object Array]' || obj[key].constructor === Object) {
          //数组,对象
          for (var arrKey in obj[key]) {
            if (Object.prototype.toString.call(obj[key][arrKey]) === '[object Array]' || obj[key][arrKey].constructor === Object) {
              //数组,对象
              for (var arrarrKey in obj[key][arrKey]) {
                str += '&' + key + '[' + arrKey + '][' + arrarrKey + ']=' + obj[key][arrKey][arrarrKey];
              }
            } else {
              //普通
              str += '&' + key + '[' + arrKey + ']=' + obj[key][arrKey];
            }
          }
        } else {
          //普通
          str += '&' + key + '=' + obj[key];
        }
      }
      return str.substring(1);
    },
    // s两个数组交集
    arrIntersection(arr1,arr2){
      if (!this.isArrayNew(arr1)) {
        return arr1.length === 0;
      }
      if (!this.isArrayNew(arr2)) {
        return arr2.length === 0;
      }
      let arrNew = arr1.filter(item => arr2.indexOf(item.value) > -1)
      return arrNew
    },
    //判断两对象是否相等
    equalsObj(obj1, obj2) {
      // 首先判断是否是引用类型
      let f1 = obj1 instanceof Object;
      let f2 = obj2 instanceof Object;
      // 如果有一个不是引用数据类型，那就进行直接判断。（内存地址不同）
      if(!f1 || !f2){
        return obj1 === obj2
      }
      // 若全是引用类型的，那就先看一下属性值的长度是否相等，若不相等，就直接false啦。
      if(Object.keys(obj1).length !== Object.keys(obj2).length){
        return false
      }
      /**
       * 若属性值的长度相等，就接着遍历里边的每一个属性，还是先看里边的属性是哪一个类型，
       * 如果全是引用类型，那就接着对里边的属性调用equals递归函数。
       * 如果不全是引用类型，那就比较这两个值是否相等，若不相等就直接false啦。
       */
      for(let p in obj1){
        let a= obj1[p] instanceof Object;
        let b= obj2[p] instanceof Object;
        if(a && b){
          this.equalsObj(obj1[p],obj2[p])
        }else if(obj1[p]!=obj2[p]){
          return false;
        }
      }
      return true;
    },

  }
}
